package com.util;


import com.exception.ServiceException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StringUtil {
    /**
     * Long对象
     * @param id
     * @return
     */
    public static Boolean isEmpty(Object id){
        if(id == null ){
            return true;
        }
        return false;
    }

    /**
     * 校验空对象
     * @param t
     * @param <T>
     */
    public static <T>  void throwEmpty(T t){
        if(t==null){
            throw new ServiceException("对象为空");
        }
    }
    public static <T>  void throwEmpty(T t ,String message){
        if(t==null){
            throw new ServiceException(message);
        }
    }

    /**
     * md5加密
     * @param str
     * @return
     */
    public static String md5(String str){
        if(StringUtils.isEmpty(str)){
            return null;
        }
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    /**
     * 获取标签中的文件地址
     * @param body
     * @return
     */
    public static String tagFileUrl(String body){
        if(StringUtils.isEmpty(body)){
            return null;
        }
        Element doc = Jsoup.parseBodyFragment(body).body();
        //图片
        List<String> list = new ArrayList<>();
        Elements pngs = doc.select("img[src]");
        for (Element element : pngs) {
            String imgUrl = element.attr("src");
            imgUrl = imgUrl.replaceAll("//104.199.199.214:9000/file-server/files/bbs/","");
            if(!imgUrl.contains("http")) {
                list.add(imgUrl);
            }
        }
        //a标签
        Elements as = doc.select("a[href]");
        for (Element element : as) {
            String imgUrl = element.attr("href");
            imgUrl = imgUrl.replaceAll("//104.199.199.214:9000/file-server/files/bbs/","");
            if(!imgUrl.contains("http")) {
                list.add(imgUrl);
            }
        }
        return list.stream().collect(Collectors.joining("&&"));
    }
}
